package com.xiashitech.agent.instrumentation.spring.refresh.inst;

import com.xiashitech.agent.cache.status.CacheStatus;
import com.xiashitech.agent.instrumentation.helper.calldepth.XSSpringRefreshCallDepth;
import com.xiashitech.agent.instrumentation.utils.BaggageUtil;
import com.xiashitech.agent.utils.DurationPrinter;
import io.opentelemetry.javaagent.bootstrap.CallDepth;
import io.opentelemetry.javaagent.extension.instrumentation.TypeInstrumentation;
import io.opentelemetry.javaagent.extension.instrumentation.TypeTransformer;
import io.opentelemetry.javaagent.shaded.io.opentelemetry.context.Context;
import io.opentelemetry.javaagent.shaded.io.opentelemetry.context.Scope;
import net.bytebuddy.asm.Advice;
import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.matcher.ElementMatcher;

import static io.opentelemetry.javaagent.bootstrap.Java8BytecodeBridge.currentContext;
import static io.opentelemetry.javaagent.extension.matcher.AgentElementMatchers.implementsInterface;
import static net.bytebuddy.matcher.ElementMatchers.*;
import static net.bytebuddy.matcher.ElementMatchers.isPublic;
import static com.xiashitech.agent.instrumentation.spring.refresh.XSSpringRefreshSingletons.instrumenter;

public class XSSpringRefreshInstrumentation implements TypeInstrumentation {
    @Override
    public ElementMatcher<TypeDescription> typeMatcher() {
        return implementsInterface(named("org.springframework.context.ConfigurableApplicationContext"));
    }

    @Override
    public void transform(TypeTransformer transformer) {
        transformer.applyAdviceToMethod(
                named("refresh").and(takesArguments(0)).and(isPublic()),
                XSSpringRefreshInstrumentation.class.getName() + "$XSRefreshAdvice");
    }

    @SuppressWarnings("unused")
    public static class XSRefreshAdvice {

        @Advice.OnMethodEnter(suppress = Throwable.class)
        public static void onEnter(
                @Advice.This Object applicationContext,
                @Advice.Local("otelCallDepth") CallDepth callDepth,
                @Advice.Local("otelContext") Context context,
                @Advice.Local("otelScope") Scope scope) {
            DurationPrinter durationPrinter = new DurationPrinter("XSSpringRefreshInstrumentation");
            if(CacheStatus.cannotRun()) {
                return;
            }
            callDepth = CallDepth.forClass(XSSpringRefreshCallDepth.class);
            if (callDepth.getAndIncrement() > 0) {
                return;
            }
            Context parentContext = currentContext();
            if (!instrumenter().shouldStart(parentContext, applicationContext)) {
                return;
            }
            parentContext = BaggageUtil.syncBaggage().build().storeInContext(parentContext);
            context = instrumenter().start(parentContext, applicationContext);
            context = BaggageUtil.syncBaggage().build().storeInContext(context);
            scope = context.makeCurrent();
            durationPrinter.printElapseDuration("XSRefreshAdvice b");
        }

        @Advice.OnMethodExit(onThrowable = Throwable.class, suppress = Throwable.class)
        public static void onExit(
                @Advice.This Object applicationContext,
                @Advice.Thrown Throwable throwable,
                @Advice.Local("otelCallDepth") CallDepth callDepth,
                @Advice.Local("otelContext") Context context,
                @Advice.Local("otelScope") Scope scope) {
            DurationPrinter durationPrinter = new DurationPrinter("XSSpringRefreshInstrumentation");
            if(CacheStatus.cannotRun()) {
                return;
            }
            if (callDepth.decrementAndGet() > 0) {
                return;
            }
            if (scope != null) {
                scope.close();
                instrumenter().end(context, applicationContext, null, throwable);
            }
            durationPrinter.printElapseDuration("XSRefreshAdvice e");
        }
    }
}
